import {loginAPI, userLogoutAPI} from '@/apis/user'
import {useCartStore} from "@/stores/cartStore.js";
import {mergeCartAPI} from "@/apis/cart.js";

export const useUserStore = defineStore('user', () => {
    // 1. 定义管理用户数据的state
    const userInfo = ref({})
    // 2. 定义获取接口数据的action函数
    const cartStore = useCartStore();
    const getUserInfo = async (user) => {
        const res = await loginAPI(user)
        userInfo.value = res.data
        //合并购物车
        await mergeCartAPI(cartStore.cartList.map(item=>{
            return{
                skuId: item.skuId,
                quantity: item.quantity
            }
        }))
        await cartStore.updateLoginCartList()
    }
    // 退出时清除用户信息
    const clearUserInfo = async () => {
            userInfo.value = {}
            cartStore.clearCart()

    }
    // 3. 以对象的格式把state和action return
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
},{
    //持久化，先下插件
    persist:true
})